<template>
  <div class="app-container">
    <span style="font-size: 26px;margin-right: 100px;">耕地轮作试点补贴</span>
    <!-- @click="saveInfo" -->
    <el-button v-if="!formDisabled" type="primary" size="medium" :loading="saveLoading" @click="saveForm">保存</el-button>
    <el-button v-if="!formDisabled && !abnormalDisabled" type="primary" plain size="medium" :loading="submitLoading"
      @click="submitForm">下一个</el-button>
    <el-button v-if="formDisabled" disabled type="info" size="medium">审核中</el-button>
    <el-form :disabled="formDisabled" ref="elForm" :model="form" :rules="rules" size="medium" label-width="130px"
      label-position="left">
      <div class="card-container">
        <el-card class="infoDiv">
          <span class="corner-label">基本信息</span>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label="身份证号码" prop="idCard">
                <el-input v-model="form.idCard" placeholder="请输入身份证号码" :maxlength="18" clearable
                  @input="calculateAgeFromIdCard" @blur="syncHistory" :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人" prop="appyBy">
                <el-input v-model="form.appyBy" placeholder="请填写姓名" clearable :style="{ width: '100%' }">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="6">
              <el-form-item label="性别" prop="sex" label-width="60px">
                <el-select v-model="form.sex" placeholder="请选择性别" clearable :style="{ width: '100%' }">
                  <el-option v-for='item in sexOptions' :label="item.label" :key="item.value"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="年龄" prop="age" label-width="60px">
                <el-input v-model="form.age" placeholder="输入年龄" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证地址" prop="idCardAddr">
                <el-input v-model="form.idCardAddr" placeholder="请输入身份证地址" clearable @blur="syncOftenAddrIfNotModified"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label="现住地址" prop="oftenAddr">
                <el-input v-model="form.oftenAddr" placeholder="请输入现住地址" clearable :style="{ width: '100%' }">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系方式" :maxlength="11" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label="一卡通账号" prop="bankCard">
                <el-input v-model="form.bankCard" placeholder="请输入一卡通账号" show-word-limit clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <div class="card-container">
        <el-card class="infoDiv">
          <span class="corner-label">轮作方式选择</span>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label="轮作方式" label-width="100px" prop="lunzuoapplytype">
                <el-checkbox-group v-model="form.lunzuoapplytype" @change="handleRotationTypesChange">
                  <div v-for="(type, index) in rotationTypeOptions" :key="type.value">
                    <el-checkbox :label="type.value">
                      {{ type.label }}
                    </el-checkbox>
                  </div>

                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label-width="200px" :label="`${year}年合计轮作补贴面积`" prop="cropall">
                <el-input :disabled="true" v-model="form.cropall" type="number" :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="" :autosize="{ minRows: 1, maxRows: 4 }"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-card>
      </div>
      <div class="card-container" v-if="form.lunzuoapplytype.includes(1)">
        <el-card class="infoDiv">
          <span class="corner-label">第一种轮作</span>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年玉米种植面积`" prop="preyuone">
                <el-input v-model="form.preyuone" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年小麦种植面积`" prop="prexiaoone">
                <el-input v-model="form.prexiaoone" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :style="{ width: '100%' }"></el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年薯类补贴面积`" prop="preshuone">
                <el-input v-model="form.preshuone" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年杂粮补贴面积`" prop="prezaone">
                <el-input v-model="form.prezaone" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年经济作物种植面积`" prop="prejinjione">
                <el-input v-model="form.prejinjione" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="green-line"></div>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label-width="300px" :label="`${year}年大豆种植补贴面积（第一种轮作）`" prop="curallone">
                <el-input :disabled="true" v-model="form.curallone" type="number" :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-card>
      </div>
      <div class="card-container" v-if="form.lunzuoapplytype.includes(2)">
        <el-card class="infoDiv">
          <span class="corner-label">第二种轮作</span>

          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label-width="400px" :label="`${lastyear}年种植玉米等其他作物、${preyear}年轮作种植大豆面积`" prop="preyutwo">
                <el-input v-model="form.preyutwo" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="green-line"></div>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label-width="300px" :label="`${year}年大豆种植补贴面积（第二种轮作）`" prop="curalltwo">
                <el-input :disabled="true" v-model="form.curalltwo" type="number" :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-card>
      </div>
      <div class="card-container" v-if="form.lunzuoapplytype.includes(3)">
        <el-card class="infoDiv">
          <span class="corner-label">第三种轮作</span>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年大豆种植面积`" prop="predathree">
                <el-input v-model="form.predathree" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年杂豆种植面积`" prop="prezathree">
                <el-input v-model="form.prezathree" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年玉米种植面积`" prop="preyuthree">
                <el-input v-model="form.preyuthree" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col> <el-col :span="12" :style="{ width: '100%' }"></el-col>
          </el-row>
          <div class="green-line"></div>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年小麦种植面积`" prop="curxiaothree">
                <el-input v-model="form.curxiaothree" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年马铃薯种植面积`" prop="curmathree">
                <el-input v-model="form.curmathree" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年甜菜种植面积`" prop="curtianthree">
                <el-input v-model="form.curtianthree" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="green-line"></div>
          <el-row :gutter="24">
            <el-col :span="24">
              <!-- <el-form-item label-width="200px" style="color:gray" label="当甜菜的前茬为马铃薯时：" /> -->
              <span style="color:gray;font-weight: bold;">当甜菜的前茬为马铃薯时：</span>
            </el-col>
          </el-row>

          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年马铃薯种植补贴面积`" prop="premathreenew">
                <el-input v-model="form.premathreenew" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年甜菜种植补贴面积`" prop="curtianthreenew">
                <el-input :disabled="true" v-model="form.curtianthreenew" type="number" :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="green-line"></div>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label-width="300px" :label="`${year}年合计种植补贴面积（第三种轮作）`" prop="curallthree">
                <el-input :disabled="true" v-model="form.curallthree" type="number" :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <div class="card-container" v-if="form.lunzuoapplytype.includes(4)">
        <el-card class="infoDiv">
          <span class="corner-label">第四种轮作</span>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年粮食作物补贴面积`" prop="preniangfour">
                <el-input v-model="form.preniangfour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${preyear}年经济作物补贴面积`" prop="prejingjifour">
                <el-input v-model="form.prejingjifour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="green-line"></div>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年花生种植补贴面积`" prop="curhuafour">
                <el-input v-model="form.curhuafour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年葵花籽种植补贴面积`" prop="curkuifour">
                <el-input v-model="form.curkuifour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年白瓜籽种植补贴面积`" prop="curbaifour">
                <el-input v-model="form.curbaifour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年油莎豆种植补贴面积`" prop="curyoushafour">
                <el-input v-model="form.curyoushafour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年油菜籽籽种植补贴面积`" prop="curyoucaifour">
                <el-input v-model="form.curyoucaifour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年芝麻种植补贴面积`" prop="curzhimafour">
                <el-input v-model="form.curzhimafour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="12">
              <el-form-item label-width="200px" :label="`${year}年胡麻籽种植补贴面积`" prop="curhumafour">
                <el-input v-model="form.curhumafour" placeholder="请输入申报土地面积" type="number" clearable
                  :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="green-line"></div>
          <el-row :gutter="24" style="margin-bottom: 10px; margin-top: 10px;">
            <el-col :span="24">
              <el-form-item label-width="400px" :label="`${year}年合计油料作物种植补贴面积（第四种轮作）`" prop="curallfour">
                <el-input :disabled="true" v-model="form.curallfour" type="number" :style="{ width: '100%' }">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-card>
      </div>


      <!-- 对于异常情况，驳回理由的显示 -->
      <div class="card-container" v-if="abnormalDisabled">
        <el-card class="infoDiv">
          <span class="corner-label" style="background-color:rgb(234, 183, 225)">驳回理由</span>
          <el-row :gutter="12">
            <el-col :span="24">
              <el-form-item label="驳回理由" prop="abnormal" label-width="80px">
                <el-input v-model="form.abnormal" type="textarea" :disabled="true" :autosize="{ minRows: 4, maxRows: 8 }"
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </el-form>
  </div>
</template>

<script>
import { queryhistoryOne, addProduce, updateProduce, submitProduce, getProduceByappNum, getProduceById, rejectProduce } from "@/api/agriculture/agriculture";

export default {
  name: "cropfarmland",
  data() {
    return {
      // 按钮loading
      saveLoading: false,
      submitLoading: false,
      formDisabled: false, //控制整个表格是否输入，false表示可以输入
      abnormalDisabled: false, //控制驳回表格是否显示
      rejectDisabled: false, //控制审批窗口是否显示
      isDisabled: true, //控制审批窗口中的驳回理由是否显示
      villageName: undefined,
      townName: undefined,
      hasUserModifiedOftenAddr: false,
      year: new Date().getFullYear(), //今年
      preyear: new Date().getFullYear() - 1,//去年
      lastyear: new Date().getFullYear() - 2, //前年

      form: {
        lunzuoapplytype: [], //轮作方式的1，2，3，4
        appyBy: undefined,
        sex: undefined,
        age: undefined,
        idCard: undefined,
        idCardAddr: undefined,
        oftenAddr: undefined,
        phone: undefined,
        bankCard: undefined,
        appType: '耕地轮作补贴',
        preyuone: 0,
        prexiaoone: 0,
        preshuone: 0,
        prezaone: 0,
        prejinjione: 0,
        curallone: 0,

        // --- 第二种轮作方式 ---
        preyutwo: 0,
        curalltwo: 0,

        // --- 第三种轮作方式 ---
        predathree: 0,
        prezathree: 0,
        preyuthree: 0,
        curxiaothree: 0,
        curmathree: 0,
        curtianthree: 0,
        premathreenew: 0,
        curtianthreenew: 0,
        curallthree: 0,

        // --- 第四种轮作方式 ---
        preniangfour: 0,
        prejingjifour: 0,
        curhuafour: 0,
        curkuifour: 0,
        curbaifour: 0,
        curyoushafour: 0,
        curyoucaifour: 0,
        curzhimafour: 0,
        curhumafour: 0,
        curallfour: 0,

        // --- 轮作总面积 ---
        cropall: 0,

        remark: undefined,
        abnormal: undefined,
        status: '待处理',
        nodeName: '',
        villageName: '',
        submitBy: '',
        year: new Date().getFullYear(),
      },
      rules: {
        lunzuoapplytype: [
          { type: 'array', required: true, message: '请至少选择一种轮作方式', trigger: 'change' }
        ],
        appyBy: [{
          required: true,
          message: '请输入申请人',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '请选择性别',
          trigger: 'change'
        }],
        age: [{
          required: true,
          message: '请输入年龄',
          trigger: 'blur'
        }],
        idCard: [{
          required: true,
          message: '请输入身份证号码',
          trigger: 'blur'
        }, {
          pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: '请输入正确的身份证号',
          trigger: 'blur'
        }],
        idCardAddr: [{
          required: true,
          message: '请输入身份证地址',
          trigger: 'blur'
        }],
        oftenAddr: [{
          required: true,
          message: '请输入现住地址',
          trigger: 'blur'
        }],
        phone: [{
          required: true,
          message: '请输入联系方式',
          trigger: 'blur'
        }, {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: '请输入正确的手机号',
          trigger: 'blur'
        }],
        bankCard: [{
          required: true,
          message: '请输入一卡通账号',
          trigger: 'blur'
        }],
        remark: [],
      },
      sexOptions: [{
        "label": "男",
        "value": "男"
      }, {
        "label": "女",
        "value": "女"
      }],
      rotationTypeOptions: [
        { "value": 1, "label": '第一种：去年种植玉米/小麦/杂粮/薯类/经济作物，今年种植大豆' },
        { "value": 2, "label": '第二种：前年种植玉米，去年种植大豆，今年种植大豆' },
        { "value": 3, "label": '第三种：去年种植大豆/杂豆/玉米，2025年种小麦/马铃薯/甜菜（其中甜菜前茬可以为马铃薯）' },
        { "value": 4, "label": '第四种：去年种植粮食作物/经济作物，今年种植油料作物（限指定市县）' }
      ],

    }
  },

  created() {
    // console.log("目前登录的角色是", this.$store.state.user.name, this.$store.state.user.roles, this.$store.state.user.permissions)
    // this.user = this.$store.state.user
    // this.userName = this.$store.state.user.name;
    this.villageName = this.$store.state.user.user.villageName;
    console.log("当前村名1", this.villageName)
    console.log("当前村名2", this.$store.state.user.roles[0])
    // this.townName = this.$store.state.user.user.townName

    if (this.$store.state.user.roles[0] == 'village') {  // 为村干部时
      this.form.nodeName = this.villageName
      this.form.villageName = this.villageName
      this.form.submitBy = this.villageName
      // this.form.townName = this.townName
      console.log("表格中的村名", this.form.villageName)
    }
    const id = this.$route.params && this.$route.params.id;
    console.log("查询工单编号4", id)
    if (id) {
      console.log("查询工单编号3", id)
      getProduceById(id).then(response => {
        console.log("查询信息", response)
        this.form = response.data;
        if (this.form.node > 1) {
          this.formDisabled = 'true'
        }
        if (this.form.node == 1 && this.form.status == '异常') {
          this.abnormalDisabled = 'true'
        }
      });
    }
  },
  computed: {
    //1.
    computedOne() {
      const { preyuone, prexiaoone, preshuone, prezaone, prejinjione } = this.form;
      var m = Math.pow(1000, 2);
      const total = (preyuone * m + prexiaoone * m + preshuone * m + prezaone * m + prejinjione * m) / m;
      return total;
    },
    // 第二种轮作方式面积合计
    computedTwo() {
      const { preyutwo } = this.form;
      const m = Math.pow(1000, 2);
      const total = (preyutwo * m) / m; // 单一作物
      return total;
    },

    // 第三种轮作方式面积合计
    computedThreePre() {
      const {
        predathree,
        prezathree,
        preyuthree,
        premathreenew,
      } = this.form;
      const m = Math.pow(1000, 2);
      const total = (
        predathree * m +
        prezathree * m +
        preyuthree * m +
        premathreenew * m
      ) / m;
      return total;
    },
    computedThreeCur() {
      const {
        curxiaothree,
        curmathree,
        curtianthree,
        curtianthreenew,
      } = this.form;
      const m = Math.pow(1000, 2);
      const total = (
        curxiaothree * m +
        curmathree * m +
        curtianthree * m +
        curtianthreenew * m
      ) / m;
      return total;
    },
    computedThreeNew() {
      const premathreenew = this.form.premathreenew;
      return premathreenew;
    },

    // 第四种轮作方式面积合计
    computedFourPre() {
      const {
        preniangfour,
        prejingjifour
      } = this.form;
      const m = Math.pow(1000, 2);
      const total = (
        preniangfour * m +
        prejingjifour * m
      ) / m;
      return total;
    },
    computedFourCur() {
      const {
        curhuafour,
        curkuifour,
        curbaifour,
        curyoushafour,
        curyoucaifour,
        curzhimafour,
        curhumafour
      } = this.form;
      const m = Math.pow(1000, 2);
      const total = (
        curhuafour * m +
        curkuifour * m +
        curbaifour * m +
        curyoushafour * m +
        curyoucaifour * m +
        curzhimafour * m +
        curhumafour * m
      ) / m;
      return total;
    },

    // 轮作总面积（四种方式之和）
    computedCropAll() {
      const curallone = this.computedOne;
      const curalltwo = this.computedTwo;
      const curallthree = this.computedThreePre;
      const curallfour = this.computedFourPre;
      // const {
      //   curallone,
      //   curalltwo,
      //   curallthree,
      //   curallfour
      // } = this.form;
      const m = Math.pow(1000, 2);
      const total = (
        curallone * m +
        curalltwo * m +
        curallthree * m +
        curallfour * m
      ) / m;
      return total;
    },
  },
  watch: {
    computedOne(newVal) {
      this.form.curallone = newVal;
    },
    computedTwo(newVal) {
      this.form.curalltwo = newVal;
    },
    computedThreePre(newVal) {
      this.form.curallthree = newVal;
    },
    computedThreeNew(newVal) {
      this.form.curtianthreenew = newVal;
    },
    computedFourPre(newVal) {
      this.form.curallfour = newVal;
    },
    computedCropAll(newVal) {
      console.log("总轮作值", newVal)
      this.form.cropall = newVal;
    },

    'form.oftenAddr'(newValue, oldValue) {
      // 注意：要防止初始同步或 blur 同步触发此 watcher 时错误地设置标记
      // 我们只关心用户主动输入导致的变化
      if (oldValue !== undefined && newValue !== oldValue) {
        // 用户修改了现住地址，标记为已自定义
        this.hasUserModifiedOftenAddr = true;
      }
    },
    '$route'(to, from) {
      const id = to.params.id;
      if (id) {
        this.fetchData(id);
      }
    }
  },

  mounted() {
    // 初始化一次
    this.form.curallone = this.computedOne;
    this.form.curalltwo = this.computedTwo;
    this.form.curallthree = this.computedThreePre;
    this.form.curallfour = this.computedFour;
    this.form.cropall = this.computedCropAll;
  },


  methods: {
    // 校验第四种轮作方式：计划面积 === 实际面积
    validateFourthRotation() {
      const pre = this.computedFourPre;
      const cur = this.computedFourCur;
      const diff = Math.abs(pre - cur);

      // 允许极小误差（如 0.001），避免浮点数问题
      if (diff < 0.01) {
        // 视为相等，并自动对齐
        // this.form.curallfour = pre; // 可选：强制同步
        return true;
      }

      this.$modal.msgError(`第四种轮作方式：前茬种植面积（${pre}亩）必须等于后茬种植面积（${cur}亩）`);
      return false;
    },
    validateThirdRotation() {
      const pre = this.computedThreePre;
      const cur = this.computedThreeCur;
      const diff = Math.abs(pre - cur);

      // 允许极小误差（如 0.001），避免浮点数问题
      if (diff < 0.01) {
        // 视为相等，并自动对齐
        // this.form.curallfour = pre; // 可选：强制同步
        return true;
      }

      this.$modal.msgError(`第三种轮作方式：前茬种植面积（${pre}亩）必须等于后茬种植面积（${cur}亩）`);
      return false;
    },
    // 🔁 新增：统一校验所有轮作规则
    validateRotationRules() {
      // 你可以根据业务决定是否需要校验第三、第四种
      // 比如：只有当选择了第三或第四种轮作时才校验

      // 示例：假设只要字段存在就校验
      const hasThird = [
        this.form.predathree,
        this.form.prezathree,
        this.form.preyuthree,
        this.form.premathreenew,
        this.form.curxiaothree,
        this.form.curmathree,
        this.form.curtianthree,
        this.form.curtianthreenew
      ].some(val => val > 0);

      if (hasThird && !this.validateThirdRotation()) {
        return false;
      }

      const hasFourth = [
        this.form.preniangfour,
        this.form.prejingjifour,
        this.form.curhuafour,
        this.form.curkuifour,
        this.form.curbaifour,
        this.form.curyoushafour,
        this.form.curyoucaifour,
        this.form.curzhimafour,
        this.form.curhumafour
      ].some(val => val > 0);

      if (hasFourth && !this.validateFourthRotation()) {
        return false;
      }
      return true; // 所有校验通过
    },
    //轮作方式的选择
    handleRotationTypesChange() {
      // 清理已移除轮作方式的配置
      const currentTypes = new Set(this.form.lunzuoapplytype)
      console.log('目前的轮作选择', this.form.lunzuoapplytype)
    },
    fetchData(id) {
      console.log("查询工单编号:", id);
      getProduceById(id).then(response => {
        this.form = response.data;
        if (this.form.node > 1) {
          this.formDisabled = 'true';
        }
        if (this.form.node === 1 && this.form.status === '异常') {
          this.abnormalDisabled = 'true';
        }
      });
    },
    syncOftenAddrIfNotModified() {
      const idCardAddr = this.form.idCardAddr.trim();
      // 只有在用户没有手动修改过 oftenAddr 的情况下才进行同步
      if (!this.hasUserModifiedOftenAddr && idCardAddr) {
        this.form.oftenAddr = idCardAddr;
      }
      // 如果身份证地址为空，也可以选择清空 oftenAddr（可选）
      // else if (!this.hasUserModifiedOftenAddr) {
      //   this.form.oftenAddr = '';
      // }
    },
    syncHistory() {
      const idCard = this.form.idCard;
      queryhistoryOne({ idCard: idCard }).then(res => {
        console.log("历史信息", res);
        if (res.idCard) {
          this.form.appyBy = res.appyBy;
          this.form.sex = res.sex;
          this.form.phone = res.phone;
          this.form.idCardAddr = res.idCardAddr;
          this.form.oftenAddr = res.oftenAddr;
          this.form.bankCard = res.bankCard;
        }

      })
    },
    calculateAgeFromIdCard() {
      const idCard = this.form.idCard.trim();
      // 清空年龄（如果身份证无效或未填满18位）
      if (!idCard || idCard.length !== 18) {
        this.form.age = '';
        return;
      }
      // 验证身份证号码格式（简单校验）
      const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
      if (!idCardRegex.test(idCard)) {
        this.form.age = '';
        return;
      }
      // 提取出生年份（身份证第7-10位）
      const birthYear = parseInt(idCard.substring(6, 10));
      // 获取当前年份
      const currentYear = new Date().getFullYear();
      // 计算年龄：当前年份 - 出生年份
      // （不考虑今年生日是否已过）
      const age = currentYear - birthYear;
      // 设置年龄
      this.form.age = age.toString();
    },
    // approveApply() {
    //     this.isDisabled = true; // 切换审核 驳回理由禁用状态 
    // },
    // rejectApply() {
    //     this.isDisabled = false; // 切换审核 驳回理由使用状态 
    // },

    getFormattedDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //保存跳转
    saveForm: function () {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (!this.validateRotationRules()) {
            return; // 校验失败，阻止提交
          }
          if (this.form.id) {
            this.saveLoading = true;
            this.form.status = "待处理";
            updateProduce(this.form).then(response => {
              this.$modal.msgSuccess("修改数据成功");
            }).finally(() => {
              this.$router.push("/agricultureProcess");
              this.saveLoading = false;
              this.resetForm();
            });
          } else {

            this.saveLoading = true;
            console.log("传入的村名", this.form.villageName)
            addProduce(this.form).then(response => {
              this.$modal.msgSuccess("保存成功");
            }).finally(() => {
              this.$router.push("/agricultureProcess");
              this.saveLoading = false;
              this.resetForm();
            });
          }
        }
      })
    },
    //保存不跳转
    submitForm: function () {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (!this.validateRotationRules()) {
            return; // 校验失败，阻止提交
          }
          if (this.form.id) {
            this.submitLoading = true;
            this.form.status = "待处理";
            updateProduce(this.form).then(response => {
              this.$modal.msgSuccess("修改数据成功");
            }).finally(() => {
              this.submitLoading = false;
              this.resetForm();
            });
          } else {

            this.submitLoading = true;
            addProduce(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            }).finally(() => {
              this.submitLoading = false;
              this.resetForm();
            });
          }

        }
      })
    },

    resetForm() {
      this.$refs['elForm'].resetFields()
    },
  }
}
</script>
<style scoped>
.app-container {
  width: 80%;
  align-items: center;
  margin-left: 10%;

  /* border: 1px solid rgb(204, 28, 28); */
}

.card-container {
  position: relative;
}

.infoDiv {
  width: 100%;
  align-items: center;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 20px;
  padding-top: 20px;
}

.green-line {
  width: 100%;
  height: 2px;
  background-color: rgb(163, 215, 30);
  /* margin: 0 10px; */
}

.corner-label {
  position: absolute;
  top: 0;
  left: 0;
  background: #81B337;
  /* 背景色 */
  color: white;
  /* 文字颜色 */
  padding: 2px 8px;
  /* 内边距 */
  font-size: 20px;
  /* 字体大小 */
  border-radius: 4px;
  /* 圆角，左上角和右下角有圆角（根据需求调整） */
  transform: translate(-10%, -10%);
  /* 微调位置，使其覆盖在圆角上 */
  /* 如果需要，可以设置z-index */
  z-index: 1;
}

::v-deep .el-checkbox__label {
  font-size: 16px;
  line-height: 18px;
  font-weight: 500;
}

::v-deep .el-checkbox__input.is-checked+.el-checkbox__label {
  color: #81B337
}

/* ::v-deep .el-checkbox__inner{
  width: 16px;
  height: 16px;
} */
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #81B337;
  border: #81B337;
  font-size: 16px;
}
</style>